//
//  TrackErrowDetailController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/10/10.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import ObjectMapper
class TrackErrowDetailController: BaseViewController {
    lazy var fenceList : [SignedDataModel] = [SignedDataModel]()
    lazy var signedPointList : [SignedDataModel] = [SignedDataModel]()
    fileprivate var signedCoorArray = [CLLocationCoordinate2D]()
    fileprivate var mapView: BMKMapView = {
        let mapView = BMKMapView()
        
        //定位精度圈
        let param = BMKLocationViewDisplayParam()
        param.isAccuracyCircleShow = false //不显示精度圈
        param.locationViewOffsetX = 0
        param.isRotateAngleValid = false//定位图标朝向失效
        param.locationViewImgName = "民工位置"//定位图标替换，需要将图片放置于mapapi.bundle/images目录
        mapView.updateLocationView(with: param)
        
        //地图配置要凡在最后才会起效
        mapView.zoomLevel = 18//比例尺级别，越小越精确
        mapView.showsUserLocation = true
        //mapView.showMapScaleBar = true//显示比例尺
        return mapView
    }()
    
    var locationService = BMKLocationService()
    
    fileprivate var recordButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.mg_noDataGray
        button.isEnabled = false
        button.titleLabel?.font = wwFont_Regular(20)
        button.layer.shadowColor = UIColor.black.cgColor
        button.layer.shadowOpacity = 0.2
        button.layer.shadowOffset = CGSize(width: 1, height: 1)
        return button
    }()
    
    //获取的签到策略
    var currentPolicyModel: RecordPolicy?
    
    /***传入变量***/
    //当前项目
    var currentProject: ProjectModel? {
        willSet {
            self.currentProject = newValue
            self.getRecordPolicyData()
        }
    }
    //当前轨迹模型
    var currentTrackModel: RecordTrack?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.mg_backgroundGray
        self.title = "轨迹异常"
        
        self.setupViews()
        self.updateViews()
        
        self.showLoadingView()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        mapView.viewWillAppear()
        self.mapView.delegate = self
        locationService.delegate = self
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        locationService.delegate = nil
        mapView.delegate = nil
        mapView.viewWillDisappear()
        WWProgressHUD.dismiss()
    }
    
    func setupViews() {
        self.view.addSubview(self.mapView)
        self.mapView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(64)
            make.height.equalTo(self.view.bounds.height * 0.56)
            
        }

        let recordButtonY = (self.view.bounds.height - self.view.bounds.height * 0.56)/2 + self.view.bounds.height * 0.56
        self.view.addSubview(self.recordButton)
        self.recordButton.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(20)
            make.right.equalTo(self.view).offset(-20)
            make.height.equalTo(50)
            make.centerY.equalTo(recordButtonY)
        }
    }
    
    func updateViews() {
        guard let model = currentTrackModel,let date = model.locateTime else {
            return
        }
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        let dateString = formatter.string(from: date)
        
        self.recordButton.setTitle("轨迹上报时间" + "  " +  dateString, for: .normal)
        
    }

    func getRecordPolicyData() {
        guard let model = self.currentProject, let aId = model.marketSupplyBaseID else {
            return
        }
        
        RecordPolicy.getRecordPolicy(aID: aId) { (response) in
            if response.success {
                self.currentPolicyModel = response.value
                
                if self.currentPolicyModel != nil {
                    self.configDestination(self.currentPolicyModel!)
                    self.configExceptionPosition()
                }
                
            }
            else {
                self.showErrorView(state: "获取签到策略失败")
            }
            
            self.locationService.stopUserLocationService()
            self.locationService.startUserLocationService()
            self.mapView.userTrackingMode = BMKUserTrackingModeFollow
            
            self.hideLoadingView()
        }
    }
    
    //配置目的地
    func configDestination(_ model: RecordPolicy) {
        self.fenceList = Mapper<SignedDataModel>().mapArray(JSONObject: model.electricFenceList)!
        self.signedPointList = Mapper<SignedDataModel>().mapArray(JSONObject: model.signedPointList)!
        var fenceCoorArr = [CLLocationCoordinate2D]()
        for (index,value) in self.fenceList.enumerated() {
            if let lat = value.Latitude, let lon = value.Longitude {
                if let doubuleLat = Double(lat), let doubleLon = Double(lon) {
                    var coor = CLLocationCoordinate2D()
                    coor.latitude = doubuleLat
                    coor.longitude = doubleLon
                    fenceCoorArr.append(coor)
                    
                }
            }
        }
        let polygon2 = BMKPolygon(coordinates: &fenceCoorArr, count: UInt(fenceCoorArr.count))
        self.mapView.add(polygon2)
        
        for (index1,value2) in self.signedPointList.enumerated() {
            if let lat = value2.Latitude, let lon = value2.Longitude {
                if let doubuleLat = Double(lat), let doubleLon = Double(lon) {
                    let annotation = BMKPointAnnotation()
                    var coor = CLLocationCoordinate2D()
                    coor.latitude = doubuleLat
                    coor.longitude = doubleLon
                    self.signedCoorArray.append(coor)
                    annotation.coordinate = coor
                    self.mapView.addAnnotation(annotation)
                    let aRadius = model.signedRange ?? "100"
                    let circlePoint = BMKCircle(center: coor, radius: Double(aRadius)!)
                    self.mapView.add(circlePoint)
                }
            }
        }
    }
    
    //配置我上传数据时的位置
    func configExceptionPosition() {
        guard let model = self.currentTrackModel else {
            return
        }
        if let lat = model.latitude, let long = model.longitude {
             if let doubuleLat = Double(lat), let doubleLon = Double(long) {
                //通过百度地图的view添加大头针
                let annotation = CustomPointAnnotation()
                annotation.identifier = "我的位置"
                var coor = CLLocationCoordinate2D()
                coor.latitude = doubuleLat
                coor.longitude = doubleLon
                annotation.coordinate = coor
                self.mapView.addAnnotation(annotation)
                self.mapView.setCenter(coor, animated: true)
            }

        }
    }
}

extension TrackErrowDetailController: BMKMapViewDelegate, BMKLocationServiceDelegate {
    func mapView(_ mapView: BMKMapView!, viewFor overlay: BMKOverlay!) -> BMKOverlayView! {
        if (overlay as? BMKCircle) != nil {
            let circleView = BMKCircleView(overlay: overlay)
            circleView?.fillColor = colorWith255RGBA(16, g: 142, b: 233, a: 0.1)
            circleView?.strokeColor = colorWith255RGBA(136, g: 191, b: 255, a: 1)
            circleView?.lineWidth = 0.5
            
            return circleView
        }
        if (overlay as? BMKPolygon) != nil {
            let polygonView = BMKPolygonView(overlay: overlay)
            polygonView?.strokeColor = UIColor(red: 0, green: 0, blue: 0.5, alpha: 1)
            polygonView?.fillColor = UIColor(red: 0.98, green: 0.63, blue: 0.07, alpha: 0.1)
            polygonView?.lineWidth = 1
            polygonView?.lineDash = true
            return polygonView
        }
        return UIView() as! BMKOverlayView
    }
    
    func mapView(_ mapView: BMKMapView!, viewFor annotation: BMKAnnotation!) -> BMKAnnotationView! {
        let AnnotationViewID = "renameMark"
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: AnnotationViewID) as BMKAnnotationView?
        if annotationView == nil {
            annotationView = BMKAnnotationView(annotation: annotation, reuseIdentifier: AnnotationViewID)
            annotationView?.frame = CGRect(x: 0, y: 0, width: 30, height: 39)//大头针大小，根据图片宽高比等比配置
            if let customAnnotation = annotation as? CustomPointAnnotation {
                if customAnnotation.identifier == "我的位置" {
                    annotationView?.image = UIImage(named: "sign_mine")
                }
//                if customAnnotation.identifier == "目标位置" {
//                    annotationView?.image = UIImage(named: "企业位置")
//                }
            }else{
                annotationView?.image = UIImage(named: "kaoqin")
                annotationView?.frame = CGRect(x: 0, y: 0, width: 3, height: 3)//大头针大小，根据图片宽高比等比配置
            }

            annotationView?.annotation = annotation
            return annotationView
        }
        return nil
    }
    
    // 用户位置更新后回调
//    func didUpdate(_ userLocation: BMKUserLocation!) {
//        self.mapView.updateLocationData(userLocation)
//        
//        let currentLocation = userLocation.location.coordinate
//        guard let model = self.currentPolicyModel else {
//            return
//        }
//        //计算两点距离
//        if let recordLat = model.latitude, let recordLon = model.longitude, let signedRange = model.signedRange {
//            if let recordLatDouble = Double(recordLat), let recordLonDouble = Double(recordLon){
//                let recordCoor = CLLocationCoordinate2D(latitude: recordLatDouble, longitude: recordLonDouble)
//                
//                let point1 = BMKMapPointForCoordinate(currentLocation)
//                let point2 = BMKMapPointForCoordinate(recordCoor)
//                let distance = BMKMetersBetweenMapPoints(point1, point2)
//            }
//            
//        }
//    }
}
